package com.cuitrip.business.comment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.comment.model.Comment;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.RatingBarView;
import com.cuitrip.service.R;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rx.TextChangeTargetEnabledSubscriber;
import com.lab.utils.ImageHelper;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created on 7/21.
 */
public class CommentActivity extends CustomUiFragmentActivity implements IProxyCallback {

    public static final int REQUEST_CODE = 0x01;
    public static final String ORDER_KEY = "CommentActivity.ORDER_KEY";
    public static final String ORDER_ID_KEY = "CommentActivity.ORDER_ID_KEY";
    @Bind(R.id.edit_count)
    TextView textCount;
    @Bind(R.id.commit_comment)
    TextView commitComment;
    private OrderItem mOrderInfo;
    private String orderId;
    private EditText mContent;
    private RatingBarView mRatingBar;
    private int ratingValue;
    private boolean isFirstComment = true;
    private ApiProxy mApiProxy = new ApiProxy(this);

    public static void start(Context context, OrderItem orderItem) {
        Jumper.launchActivity(context, new Intent(context, CommentActivity.class)
                .putExtra(ORDER_KEY, orderItem));
    }

    public static void start(Context context, String orderId) {
        Jumper.launchActivity(context, new Intent(context, CommentActivity.class)
                .putExtra(ORDER_ID_KEY, orderId));
    }

    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }
        if (intent.hasExtra(ORDER_ID_KEY)) {
            orderId = intent.getStringExtra(ORDER_ID_KEY);
        } else {
            mOrderInfo = (OrderItem) intent.getSerializableExtra(ORDER_KEY);
            if (mOrderInfo == null) {
                finish();
                return;
            }
        }
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        isFirstComment = !userInfo.hasAlreadyNpsInfo();
        super.onCreate(savedInstanceState, R.layout.ct_order_comment);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        mContent = (EditText) findViewById(R.id.content);
        mRatingBar = (RatingBarView) findViewById(R.id.comment_score);
        RxTextView
                .textChangeEvents(mContent)
                .subscribe(addSubscriber(new TextChangeTargetEnabledSubscriber().setTarget(commitComment)));

        /**
         * 如果是用户第一次打分显示为next，否则则显示submit
         */
        if (isFirstComment) {
            commitComment.setText(R.string.operation_next);
        } else {
            commitComment.setText(R.string.review_operation_review);
        }
    }


    @OnClick(R.id.commit_comment)
    void commitComment() {
        if (isFirstComment) {
            Comment comment = new Comment();
            comment.setOrderId(mOrderInfo.getOid());
            comment.setRating(String.valueOf(ratingValue));
            comment.setText(mContent.getText().toString());
            comment.setSid(mOrderInfo.getSid());
            comment.setNickName(mOrderInfo.getUserNick());
            comment.setTargetId(mOrderInfo.getTargetId());
            Intent intent = new Intent(this, NPSRateActivity.class).putExtra(NPSRateActivity.COMMENT_KEY, comment);
            Jumper.launchActivityForResult(this, intent, REQUEST_CODE);
        } else {
            showNoCancelDialog();
            OrderBusiness.submitReview(mApiProxy, mOrderInfo.getOid(), String.valueOf(ratingValue), mContent.getText().toString());
        }
    }


    private void bindData() {
        setViewText(R.id.ct_service_name_tv, mOrderInfo.getServiceName());
        setViewText(R.id.author_name, mOrderInfo.getInsiderName());
        setViewText(R.id.simple_info, mOrderInfo.getServiceAddress());
        ImageHelper.displayCtImage(mOrderInfo.getServicePIC(), (ImageView) findViewById(R.id.service_pic), null);
        textCount.setText(getString(R.string.txt_count_format, mContent.getText().length(), 1500));
    }

    public void initData() {
        if (mOrderInfo != null) {
            bindData();
        } else {
            showLoading();
            OrderBusiness.getOrderInfo(mApiProxy, orderId);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            finish();
        }
    }

    @Override
    public void initListener() {
        mRatingBar.setOnRatingListener(new RatingBarView.OnRatingListener() {


            @Override
            public void onRating(Object bindObject, int RatingScore) {
                ratingValue = RatingScore;
            }
        });

        mContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                try {
                    int nSelStart = 0;
                    int nSelEnd = 0;
                    boolean nOverMaxLength = false;
                    nSelStart = mContent.getSelectionStart();
                    nSelEnd = mContent.getSelectionEnd();
                    nOverMaxLength = (editable.length() > 1500) ? true : false;
                    textCount.setText(getString(R.string.txt_count_format, editable.length(), 1500));
                    if (nOverMaxLength) {
                        editable.delete(nSelStart - 1, nSelEnd);
                        mContent.setTextKeepState(editable);
                        return;
                    }
                } catch (Exception e) {
                    AppLog.w(e.toString());
                }
            }
        });
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mTopbarLeftAreaName = getString(R.string.back_icon);
        customUiConfig.mTopbarMiddleAreaName = getString(R.string.review);
        return customUiConfig;
    }

    private void handleOrderInfoResult(CtApiResponse response) {
        if (response.isResponseNormal()) {
            if (response.result instanceof OrderItem) {
                hideLoading();
                try {
                    mOrderInfo = (OrderItem) response.result;
                    bindData();
                } catch (Exception e) {
                    LogHelper.e("omg", e.getMessage());
                }
            }
        } else {
            hideLoading();
            if (!TextUtils.isEmpty(response.msg)) {
                ToastUtil.toast(response.msg);
            }
            finish();
        }

    }

    private void handleSubmitReviewResult(CtApiResponse response) {
        hideNoCancelDialog();
        if (response.isResponseNormal()) {
            navigate2NextPage();
            sendBroadcast(
                    new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));
        } else {
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }

    }

    private void navigate2NextPage() {
        Comment comment = new Comment();
        comment.setOrderId(mOrderInfo.getOid());
        comment.setRating(String.valueOf(ratingValue));
        comment.setText(mContent.getText().toString());
        comment.setSid(mOrderInfo.getSid());
        comment.setTargetId(mOrderInfo.getTargetId());
        comment.setNickName(mOrderInfo.getUserNick());
        Intent intent = new Intent(CommentActivity.this, CommentSuccessActivity.class)
                .putExtra(NPSRateActivity.COMMENT_KEY, comment);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_ORDER_INFO.equals(response.getApiName())) {
            handleOrderInfoResult(response);
        } else if (ApiManager.SUBMIT_COMMENT.equals(response.getApiName())) {
            handleSubmitReviewResult(response);
        }
        return false;
    }
}
